package com.ineatconseil.yougo.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ineatconseil.yougo.bo.Request;
import com.ineatconseil.yougo.bo.RequestStatus;
import com.ineatconseil.yougo.bo.User;
import com.ineatconseil.yougo.dao.UserDao;

@Repository("userDao")
@Transactional
public class UserDaoHibernate extends GenericDaoHibernate<User, Long> implements
		UserDao {

	public UserDaoHibernate() {
		super(User.class);
	}

	public User findByLogin(String login) {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createCriteria(User.class)
				.add(Restrictions.eq("login", login));

		return (User) criteria.uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<User> findByRequests(Date beginDate, Date endDate,
			List<RequestStatus> requestStatus) {
		DetachedCriteria availableRequestsCriteria = DetachedCriteria
				.forClass(Request.class)
				.add(Restrictions.ge("start", beginDate))
				.add(Restrictions.le("end", endDate))
				.add(Restrictions.in("status", requestStatus));

		Criteria criteria = getHibernateTemplate()
				.getSessionFactory()
				.getCurrentSession()
				.createCriteria(User.class)
				.add(Property.forName("requests").in(availableRequestsCriteria));

		return criteria.list();
	}

}
